package com.yanx.common.core.domain.manager;

import com.yanx.common.core.domain.entity.IBaseLogicEntity;
import com.yanx.common.core.domain.repository.BaseLogicRepository;

import java.io.Serializable;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

public class BaseLogicManager<E extends IBaseLogicEntity, R extends BaseLogicRepository> extends BaseManager<E, R> {

    //invaild
    public <ID extends Serializable> void invaildById(ID id) {
        this.findById(id).ifPresent(entity -> {
            entity.setDeleted(true);
            this.save(entity);
        });
    }

    public <ID extends Serializable> void invaildById(Iterable<ID> ids) {
        Iterable<E> all = this.getAll(ids);
        all.forEach(entity -> {
            entity.setDeleted(true);
        });
        this.saveAll(all);
    }

    public <ID extends Serializable> void invaildById(ID[] ids) {
        this.invaildById(Arrays.asList(ids));
    }

    public void invaild(E entity) {
        entity.setDeleted(true);
        this.save(entity);
    }

    public void invaild(Iterable<E> entitys) {
        entitys.forEach(e -> e.setDeleted(true));
        this.saveAll(entitys);
    }

    public void invaild(E[] entitys) {
        this.invaild(Arrays.asList(entitys));
    }

    //find
    @Override
    public <ID extends Serializable> Optional<E> findById(ID id) {
        return super.findById(id).filter(u -> !u.getDeleted());
    }

    @Override
    public List<E> getAll() {
        return super.getAll().stream().filter(u -> !u.getDeleted()).collect(Collectors.toList());
    }

    @Override
    public <ID extends Serializable> List<E> getAll(Iterable<ID> ids) {
        return super.getAll(ids).stream().filter(u -> !u.getDeleted()).collect(Collectors.toList());
    }
}
